﻿using System;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using System.Text;
using Devv.Core.UniDataTier;

namespace BikeBouncer.BusinessLayer.Entities
{
	[DataContract, Serializable]
	public class City : BaseEntity
	{
		#region Properties
		
		[DataMember]
		public String Title { get; set; }

		[DataMember]
		public String Region { get; set; }

		[DataMember]
		public String Country { get; set; }
		
		#endregion

		#region Constructor

		public City()
		{
		}

		public City(Int32 id)
		{
			Construct(DataAccess.City_Get(id));
		}

		public City(SqlDataReader reader)
		{
			Construct(reader);
		}

		#endregion

		#region Loading

		public override void Load(SqlDataReader reader)
		{
			Id = DataHandler.GetInt32(reader, "CityId");
			Title = DataHandler.GetString(reader, "CityTitle");
			Region = DataHandler.GetString(reader, "CityRegion");
			Country = DataHandler.GetString(reader, "CityCountry");
			Active = DataHandler.GetBoolean(reader, "CityActive");
		}

		public static City Fetch(String text)
		{
			City c;
			String[] arr = text.Split(",".ToCharArray());
			
			if (arr.Length == 1)
			{
				arr = text.Split(" - ".ToCharArray());
			}

			String title = arr[0].Trim();
			String region = String.Empty;
			String country = String.Empty;

			if (arr.Length == 2)
			{
				String s = arr[1].Trim();

				if (s.Length == 2)
				{
					country = s.ToUpper();
				}
			}
			else if (arr.Length == 3)
			{
				region = arr[1].Trim();
				country = arr[2].Trim();
			}

			if (String.IsNullOrEmpty(country))
			{
				country = Settings.DefaultCountry;
			}

			c = new City(DataAccess.City_GetExact(title, region, country));
 
			if (c.Id < 1)
			{
				c.Title = title;
				c.Region = region;
				c.Country = country;
			}

			return c;
		}

		#endregion

		#region ToString

		public new String ToString()
		{
			return ToString(Environment.NewLine);
		}

		public String ToString(String separator)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append(Title + separator);

			if (!String.IsNullOrEmpty(Region))
			{
				sb.Append(Region + separator);
			}

			if (!String.IsNullOrEmpty(Country))
			{
				sb.Append(Country + separator);
			}

			return sb.ToString(0, sb.Length - separator.Length);
		}

		#endregion
	}
}